﻿using System;
using System.Data.SQLite;
using CompactMapper.Orm.Contracts;

namespace CompactMapper.Orm.UnitOfWork
{
    internal class CompactMapperTransaction : ISqliteTransaction
    {
        private readonly ConnectionFactory.ConnectionWrapper _connectionWrapper;
        private readonly SQLiteTransaction _transaction;
        public CompactMapperTransaction(String connectionString)
        {
            _connectionWrapper = ConnectionFactory.CreateConnection(connectionString);
            _transaction = _connectionWrapper.Connection.BeginTransaction();
        }

        public void Dispose()
        {
            try
            {
                _transaction.Commit();
            }
            catch
            {
                _transaction.Rollback();
            }
            finally
            {
                _transaction.Dispose();
                _connectionWrapper.Dispose();
            }
        }

        public void ExecuteNonQuery(SQLiteCommand command)
        {
            if (command == null)
                return;

            command.Connection = _connectionWrapper.Connection;
            command.ExecuteNonQuery();
        }
    }
}